import { useEffect, useRef, useState } from 'react'
type nodeType = Node & ParentNode

export const usePopupVisible = (initState: boolean) => {
	const [popupVisible, setPopupVisible] = useState(initState)
	const targetRef = useRef<nodeType | null>(null)
	useEffect(() => {
		//参数说明:child表示指定某个节点,parent表示child节点是否存在于parent节点中
		const isChildOf = (child: nodeType | null, parent: nodeType) => {
			let myParentNode = child
			while (myParentNode) {
				if (myParentNode === parent) {
					return true
				} else {
					myParentNode = myParentNode.parentNode
				}
			}
			return false
		}

		const handleClick = (e: MouseEvent): any => {
			// 找父级是否有 virtual-select
			const popup = document.querySelector('.rc-trigger-popup')
			const child = e.target as nodeType
			if (
				child &&
				popup &&
				!isChildOf(child, popup) &&
				targetRef.current &&
				!isChildOf(child, targetRef.current)
			) {
				setPopupVisible(false)
			}
		}

		document.addEventListener('click', handleClick)
		return () => document.removeEventListener('click', handleClick)
	}, [])

	const showPopup = (e: React.MouseEvent) => {
		// e.nativeEvent.stopImmediatePropagation()
		targetRef.current = e.nativeEvent.target as nodeType
		setPopupVisible((value) => !value)
	}

	const hidePopup = (e: React.MouseEvent) => {
		setPopupVisible(false)
	}

	return [popupVisible, showPopup, hidePopup] as const
}
